#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
清理临时学生记录
删除所有以 "Temp_" 开头的学生记录
"""

import json
import requests
import sys

# 禁用 SSL 警告
requests.packages.urllib3.disable_warnings()

# Odoo 服务器配置
ODOO_URL = "https://naturedao.tech"
API_KEY = "298a4b1128cb1bdb8da2bb87e0e9c11e9b82850f"
DATABASE = "odootest"
USERNAME = "yan.gao@ccwin-in.com"


def authenticate():
    """使用 API Key 获取用户 ID"""
    url = f"{ODOO_URL}/jsonrpc"
    
    payload = {
        "jsonrpc": "2.0",
        "method": "call",
        "params": {
            "service": "common",
            "method": "authenticate",
            "args": [DATABASE, USERNAME, API_KEY, {}]
        },
        "id": 1
    }
    
    response = requests.post(url, json=payload, verify=False)
    result = response.json()
    
    return result.get('result')


def call_odoo(uid, model, method, args=None, kwargs=None):
    """调用 Odoo API"""
    if args is None:
        args = []
    if kwargs is None:
        kwargs = {}
    
    url = f"{ODOO_URL}/jsonrpc"
    
    payload = {
        "jsonrpc": "2.0",
        "method": "call",
        "params": {
            "service": "object",
            "method": "execute_kw",
            "args": [DATABASE, uid, API_KEY, model, method, args, kwargs]
        },
        "id": 1
    }
    
    response = requests.post(url, json=payload, verify=False)
    result = response.json()
    
    if 'error' in result:
        print(f"错误: {result['error']}")
        return None
    
    return result.get('result')


def find_temp_students(uid):
    """查找所有临时学生记录"""
    print("正在查找临时学生记录...")
    
    # 搜索名称以 "Temp_" 开头的记录
    students = call_odoo(
        uid,
        'hostel.student',
        'search_read',
        args=[[('name', 'ilike', 'Temp_%')]],
        kwargs={'fields': ['id', 'name', 'create_date']}
    )
    
    return students


def delete_students(uid, student_ids):
    """删除学生记录"""
    print(f"正在删除 {len(student_ids)} 条记录...")
    
    result = call_odoo(
        uid,
        'hostel.student',
        'unlink',
        args=[student_ids]
    )
    
    return result


def main():
    """主函数"""
    print("=" * 80)
    print("清理临时学生记录脚本")
    print("=" * 80)
    print(f"服务器: {ODOO_URL}")
    print(f"数据库: {DATABASE}")
    print("=" * 80)
    
    try:
        # 1. 认证
        print("\n正在认证...")
        uid = authenticate()
        
        if not uid:
            print("✗ 认证失败")
            return
        
        print(f"✓ 认证成功！用户 ID: {uid}")
        
        # 2. 查找临时记录
        temp_students = find_temp_students(uid)
        
        if not temp_students:
            print("\n✓ 没有找到临时记录，数据库很干净！")
            return
        
        print(f"\n找到 {len(temp_students)} 条临时记录：")
        print("-" * 80)
        for student in temp_students:
            print(f"  ID: {student['id']:<6} 姓名: {student['name']:<30} 创建时间: {student.get('create_date', 'N/A')}")
        print("-" * 80)
        
        # 3. 确认删除
        confirm = input(f"\n确认删除这 {len(temp_students)} 条临时记录？ (yes/no): ").strip().lower()
        
        if confirm not in ['yes', 'y', '是']:
            print("✗ 操作已取消")
            return
        
        # 4. 删除记录
        student_ids = [s['id'] for s in temp_students]
        result = delete_students(uid, student_ids)
        
        if result:
            print(f"\n✓ 成功删除 {len(student_ids)} 条临时记录！")
        else:
            print("\n✗ 删除失败")
        
    except Exception as e:
        print(f"\n✗ 错误: {str(e)}")
        import traceback
        traceback.print_exc()


if __name__ == "__main__":
    main()

